<?php
namespace app\api\controller\Common;

use app\api\controller\Base;
use app\api\controller\Baseuser;

use app\api\controller\mytool\Wechat;
use app\common\model\customer\Customer;
use app\common\model\customer\Subscribe;
use app\common\model\user\Setting;
use app\common\model\user\TaskLog;
use app\common\model\user\User;
use think\facade\Request;

class Task extends Base
{
    // 预约提醒
    public function subscribeMessage()
    {
        //查询快到时间的预约信息（两个小时）
        $t = time();
        $where[] = ['status', '=', '1'];
        $where[] = ['SubscribeTime', '<', $t + 2*60*60];
        $subscribe = (new Subscribe)->getList($where);
        if ($subscribe) {
            $tasklogModel = new TaskLog();
            $customerModel = new Customer();
            foreach($subscribe as $item) {
                // 判断是否已经发送模板消息，如果发送则不再重新发送
                $taskCount = $tasklogModel->where('Content', $item['SubscribeId'])
                    ->where('UserId', $item['BussinessId'])->count();
                if($taskCount == 0) {

                    // 查询业务员openid
                    $openid = (new User())->where('UserId', $item['BussinessId'])->value('WechatId');
                    if(!empty($openid)) {
                        $customer = $customerModel->where('CustomerId', $item['CustomerId'])->find();

                        $data = [
                            'temp' => WECHATTEMP1,
//                        'temp' => 'vYN958jfxpZ03CDLMelS4EQhC8jWJCq5tZmzdYQpC_k',
                            'msgdata' => [
                                'first'    => '预约回访提醒',
                                'keyword1' => $item['SubscribeTime'],
                                'keyword2' => $customer['UserName'],
                                'remark'   => $item['Content']
                            ],
                            'touser' => [$openid]
//                        'touser' => ['o0FOt5z4NLJ7YpNh_8O-sSmo8-rg']

                        ];
                        // 发送模板消息
                        $res = Wechat::SendMessage($data);
                        // 保存记录
                        (new TaskLog())->saveData([
                            'Type' => 1,
                            'Content' => $item['SubscribeId'],
                            'UserId' => $item['BussinessId'],
                            'ResContent' => json_encode($res)
                        ]);
                    }
                }
            }
        }
    }

    // 日报提醒
    public function reportMessage()
    {
        // 获取今天的日期
        $t = time();
        $currentDate = date('Y-m-d', $t);

        // 查询跳过日期
        $date = (new Setting())->getSetting('work');
        $workDate = [];
        if ($date) {
            $workDate = json_array($date['Content'], true);
        }

        if ($workDate !=[]) {

            if ($workDate['restDay'] == true) {
                // 判断今天是否是周末
                $index = date('w', strtotime($currentDate));
                if ($index == 0 || $index == 6) {
                    return moerr('跳过日期');
                }
            }

            // 剔除所有指定日期
            if (count($workDate['dates']) > 0) {
                $label = false;
                for($i = 0; $i<count($workDate['dates']); $i++) {
                    if($workDate['dates'][$i]['date'] == $currentDate) {
                        $label = true;
                        break;
                    }
                }
                if ($label) {
                    return moerr('跳过日期');
                }
            }

            // 查询填写日报的用户
            $where[] = ['State', '=', '1'];
            $where[] = ['Role', 'in', [201]];
            $users = (new User())->where($where)->select();
            if (count($users) > 0) {
                $tasklogModel = new TaskLog();
                foreach($users as $item) {
                    if (!empty($item['WechatId'])) {
                        // 判断是否已经发送模板消息，如果发送则不再重新发送
                        $taskCount = $tasklogModel->where('Content', $currentDate)->where('UserId', $item['UserId'])->count();
                        if($taskCount == 0) {
                            $data = [
                                'temp' => WECHATTEMP1,
//                            'temp' => 'vYN958jfxpZ03CDLMelS4EQhC8jWJCq5tZmzdYQpC_k',
                                'msgdata' => [
                                    'first'    => '日报提交提醒',
                                    'keyword1' => date('Y-m-d H:i:s',time()),
                                    'keyword2' => '提交日报',
                                    'remark'   => '提交日报',
                                ],
                                'touser' => [$item['WechatId']]
//                            'touser' => ['o0FOt5z4NLJ7YpNh_8O-sSmo8-rg']
                            ];
                            // 发送模板消息
                            $res = Wechat::SendMessage($data);
                            // 保存记录
                            (new TaskLog())->saveData([
                                'Type' => 2,
                                'Content' => $currentDate,
                                'UserId' => $item['UserId'],
                                'ResContent' => json_encode($res)
                            ]);
                        }
                    }

                }
            }
        } else {
            return moerr('请先设置参数');
        }
    }

}
